<script lang="ts" setup>
import userHome from '@/views/home/userHome.vue'
import imgUploader from '@/views/component/imgUploader.vue'
import {useRoute} from "vue-router";
import {ref, onBeforeMount, onMounted, computed} from 'vue'
import {getCommentsByNidAPI,
  getNoteDetailAPI,
  sendCommentAPI,
  deleteNoteByNidAPI,
  deleteCommentAPI,
  getNotesByUidAPI,
  updateNoteAPI} from "@/apis/notes"
import {sendMessageAPI} from '@/apis/message'
import {ElMessage, ElMessageBox} from "element-plus";
import {useUserStore} from "@/stores/user";
import { Delete, Refresh, Top } from '@element-plus/icons-vue'
import postNote from '@/views/common/postNote.vue'
import {formatDateToDetail,formatDateToYYMMDD} from '@/utils/formatDate'

const data=ref({})
const commentList = ref([])
const isShow=ref(false)
const route=useRoute()
import router from '@/router/index'
const showReplyInput = ref<number | null>(null)
const replyContent = ref('')//二级回复内容
const expandedComments = ref<number[]>([])//展开的评论
const userStore=useUserStore()
const isAdmin=userStore.getToken()&&userStore.getUserInfo().role==='ADMIN'
const dialogVisible = ref(false)

let tempData

const clueForm = ref({
  name: '',
  contact: '',
  details: '',
  imgUrl: ''
})

async function getNoteDetail() {
  await getNoteDetailAPI(route.params.nid).then(res=>{
    if(res.data===null){
      ElMessage.error('帖子不存在')
      router.push('/')
      return
    }
    data.value=res.data
    isShow.value=true
  })

  //如果已登录
  if(userStore.getToken()){
    await getNotesByUidAPI(userStore.getUserInfo().uid).then(res=>{
      res.data.forEach(item=>{
        if(item.nid===data.value.nid){
          isMyPost.value=true
          return
        }
      })
    })
  }
}

//获取所有评论
async function getNoteComments() {
  await getCommentsByNidAPI(route.params.nid).then(res=>{
    commentList.value=res.data
  })
  if(commentList.value.length>0){
    //不超过10条回复的评论自动展开，超过的默认收起
    commentList.value.forEach(item=>{
      if(item.replies.length<=10)
        expandedComments.value.push(item.discussId)
    })
  }
}
const isMyPost=ref(false)

onMounted( ()=>{
  getNoteDetail()
  getNoteComments()
})

const comment=ref('')


//发送消息
async function sendMessage(targetUid:number,type:string) {
  if(targetUid===userStore.getUserInfo().uid){
    return
  }
  await sendMessageAPI({
    content:type==='comment'?comment.value:replyContent.value,
    sender:userStore.getUserInfo().uid,
    receiver:targetUid,
    title:userStore.getUserInfo().name,
    type:'comment',
    createdDate:new Date().getTime(),
    isRead:0
  }).then(res=>{
    if(res.code==='200')
      console.log('send message successfully')
  })
}

//评论
async function sendComment() {
  const commentData = {
    nid: route.params.nid,
    content: comment.value,
    publisherName: useUserStore().getUserInfo().name,
    createTime: new Date().getTime(),
    userId: useUserStore().getUserInfo().uid,
    lastId: ''
  }
  await sendCommentAPI(JSON.stringify(commentData)).then(res=>{
    ElMessage({
      type:res.code==='200'?'success':'error',
      message:res.code==='200'?'发布成功':res.msg
    })
    if(res.code==='200'){
      comment.value=''
      //重新获取数据
      getNoteComments()
    }
  })
}

//回复评论
async function replyComment(parentId) {
  const replyData = {
    nid: route.params.nid,
    content: replyContent.value,
    publisherName: useUserStore().getUserInfo().name,
    createTime: new Date().getTime(),
    userId: useUserStore().getUserInfo().uid,
    lastId: parentId
  }
  await sendCommentAPI(JSON.stringify(replyData)).then(res => {
    ElMessage({
      type: res.code === '200' ? 'success' : 'error',
      message: res.code === '200' ? '回复成功' : res.msg
    })
    if (res.code === '200') {
      replyContent.value = ''
      showReplyInput.value = null
      //刷新数据
      getNoteComments()
    }
  })
}

function submitComment() {
  if(!userStore.getToken()){
    ElMessage.warning('登录后可回复')
    return
  }
  if (comment.value==='') {
    ElMessage.warning('内容不能为空！')
    return
  }
  //发送评论
  sendComment()
  //发送消息
  sendMessage(data.value.uid,'comment')
}

function toggleReplyInput(discussId: number) {
  showReplyInput.value = showReplyInput.value === discussId ? null : discussId
  replyContent.value = ''
}

function submitReply(parentId: string,uid:number) {
  if(!userStore.getToken()){
    ElMessage.warning('登录后可回复')
    return
  }
  if (replyContent.value === '') {
    ElMessage.warning('回复内容不能为空！')
    return
  }
  //回复评论
  replyComment(parentId)
  //发送消息给用户
  sendMessage(uid,'reply')
}

//收起回复
function toggleReplies(discussId: number) {
  const index = expandedComments.value.indexOf(discussId)
  if (index === -1) {
    expandedComments.value.push(discussId)
  } else {
    expandedComments.value.splice(index, 1)
  }
}

function deleteNote() {
  ElMessageBox.confirm('确认要删除这篇帖子吗', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
    const res = await deleteNoteByNidAPI(route.params.nid)
    ElMessage({
      type: res.code==='200'?'success':'error',
      message: res.code==='200'?'删除成功':'删除失败',
    })
    if(res.code==='200'){
      router.push('/')
    }
  })
}

//关闭帖子
function openAndCloseNote(mode:string) {
  ElMessageBox.confirm(
      mode==='close'?'确认要关闭这篇帖子吗，关闭后用户将不能再提交线索':'确认解锁吗',
      mode==='close'?'警告':'提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    let tempData=data.value
    tempData.status=mode==='close'?1:0
    await updateNoteAPI(tempData).then(res=>{
      if(res.code==='200'){
        ElMessage.success(mode==='close'?'帖子已关闭':'帖子已解锁')
        //刷新
        getNoteDetail()
      }
    })
  })
}


const mode=ref('post')

function handleEditNote() {
  mode.value='edit'
  tempData=data.value
  dialogVisible.value = true
}


function handlePostNote() {
  if (!userStore.getToken()) {
    ElMessage.warning('请先登录')
    return
  }
  mode.value='post'
  dialogVisible.value = true
}

function refreshPage() {
  // 刷新当前页面数据
  getNoteDetail()
  getNoteComments()
  ElMessage.success('刷新成功')
  //回到顶部
  scrollToTop()
}

function scrollToTop() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
}

function deleteComment(discussId: string) {
   ElMessageBox.confirm('确认要删除这条评论吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async ()=>{
     const res = await deleteCommentAPI(discussId)
     ElMessage({
       type: res.code === '200' ? 'success' : 'error',
       message: res.code === '200' ? '删除成功' : '删除失败',
     })
     if (res.code === '200') {
       // 重新获取评论列表
       getNoteComments()
     }
   })
}

const postNoteRef=ref(null)

function handleDialogClose() {
  postNoteRef.value.resetData()
  dialogVisible.value=false
}

// 获取子组件的图片上传结果
function handleImageUploaded(url: string) {
  clueForm.value.imgUrl = url
}

async function submitClue() {
  if(!userStore.getToken()){
    ElMessage.warning('请先登录后再提交线索')
    return
  }
  
  if(!clueForm.value.name || !clueForm.value.contact || !clueForm.value.details) {
    ElMessage.warning('请填写完整的线索信息')
    return
  }
  ElMessageBox.confirm('请确认线索无误后提交', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        //TODO check
    //发送消息给用户
    sendClueMessage()
    //照片识别
  })

 async function sendClueMessage() {
   if(data.value.uid===userStore.getUserInfo().uid){
     return
   }
    await sendMessageAPI({
      content:`${clueForm.value.details}，请联系我：${clueForm.value.contact}`,
      sender:userStore.getUserInfo().uid,
      receiver:data.value.uid,
      title:userStore.getUserInfo().name,
      type:'clue',
      createdDate:new Date().getTime(),
      isRead:0
    }).then(res=>{
      if(res.code==='200'){
        ElMessage.success('提交成功')
        //重置表单
        clueForm.value = {
          name: '',
          contact: '',
          details: '',
          imgUrl: ''
        }
      }
    })
  }
}
</script>

<template>
  <div class="page">
    <div class="header">
      <userHome></userHome>
    </div>
    <div class="body">
      <div class="dataTable" >
        <div v-if="isShow">
        <div class="header" style="width: 100%;min-height: 120px;height:auto;text-align: center;margin-bottom: 15px">
          <h1 style="color: #F64848">{{ data.title}}</h1>
          <span>{{ data.describe }}</span>
        </div>
        <div style="width: 100%;height: auto;display: flex;flex-direction: row">
          <div class="left">
            <img :src="data.imgUrl" alt="" style="width: 400px;height: 500px">
          </div>
          <div class="right" style="margin-left: 50px;width: 100%;">
            <el-descriptions title="失踪人信息" :border="true" column="2">
            <el-descriptions-item label="姓名">{{ data.seekerName }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ data.sex==='male'?'男':'女' }}</el-descriptions-item>
            <el-descriptions-item label="年龄">{{ data.age }}</el-descriptions-item>
            <el-descriptions-item label="失踪日期">{{ formatDateToYYMMDD(data.missingDate) }}</el-descriptions-item>
            <el-descriptions-item label="失踪地点">{{ data.missingAddress }}</el-descriptions-item>
            <el-descriptions-item label="身高(cm)">{{ data.height }}</el-descriptions-item>
          </el-descriptions>
          <h4>提供线索</h4>
          <div style="display: flex;flex-direction: row">
            <imgUploader></imgUploader>
            <div style="margin-left: 10px;display: flex;width: 100%;flex-direction: column;gap: 10px">
              <el-input v-model="clueForm.name" placeholder="姓名"></el-input>
              <el-input v-model="clueForm.contact" placeholder="联系方式"></el-input>
              <el-input 
                v-model="clueForm.details" 
                type="textarea" 
                rows="4" 
                placeholder="请填写您知道的线索详情">
              </el-input>
            </div>
          </div>
            <el-button v-if="data.status==='0'&&!isMyPost" class="submit-clue-button" @click="submitClue">提交</el-button>
            <el-tooltip v-else
                class="box-item"
                effect="dark"
                :content="isMyPost?'不能提交自己发布的帖子':'帖子已关闭'"
                placement="bottom"
            >
              <el-button class="ban-submit-clue-button" >提交</el-button>
            </el-tooltip>

        </div>
      </div>
          <div style="text-align: center;margin-top: 5px">
            <span style="font-size: 12px;color: #989696">发布于{{formatDateToYYMMDD(data.createdDate)}}</span>
            <span style="font-size: 12px;color: #989696;margin-left: 20px">
              温馨提示
            1、留言后登记人会立即收到您的线索留言
            2、登记人预留手机号会收到短信线索提醒
            3、请您遵守国家法律法规，您对您的留言负有法律责任
            </span>

          </div>
        </div>

        <div v-else>
          <el-skeleton style="width: 100%" direction="vertical" alignment="flex-start" :loading="loading" animated class="content-skeleton">
            <template #template>
              <el-skeleton-item variant="h1" style="width: 50%;" />
              <el-skeleton-item variant="h1" style="width: 70%;" />
              <el-skeleton-item variant="h1" style="width: 100%;" />
              <el-skeleton-item variant="rect" style="width: 100%; height: 500px; background-color: #aaa;" />
              <div style="padding: 12px 14px 0 0">
                <el-skeleton-item variant="h1" style="width: 100%;" />

              </div>
            </template>
          </el-skeleton>
        </div>

    </div>

      <div class="notice">
        <h3>温馨提示</h3>
        <p>1、在此善意提醒发布者审慎管理个人信息，切勿轻信陌生人的电话，谨防上当受骗。</p>
        <p>2、所有信息（寻人启事资料、照片、留言等）均由发布者提供，如侵犯任何第三人的肖像权、隐私权或其他合法权益，请联系本网站删除。</p>
        <p>3、本寻人平台恳请各地区爱心人士转发此寻人启事，您的举手之劳就可能促成一个家庭的团圆，并请您看到寻人启事中的被寻人后对其予以必要的协助</p>
      </div>

    <div class="discussArea">
      <h3>讨论区</h3>
      <el-input type="textarea" placeholder="在这里添加您的评论" v-model="comment" rows="4"></el-input>
      <div style="text-align:right;">
        <el-button type="primary" @click="submitComment" style="margin-top: 10px;margin-bottom: 10px;">发布</el-button>
      </div>
      
      <div v-if="commentList.length===0">
        <el-empty description="暂无讨论"></el-empty>
      </div>

      <div v-else v-for="item in commentList" :key="item.discussId" class="comment">
        <div class="comment-header">
          <div class="user-info">
            <el-avatar :size="40" :src="item.avatar?item.avatar:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"></el-avatar>
            <h4 class="comment-author">{{ item.publisherName }}:</h4>
          </div>
          <div>
            <el-button type="text" @click="toggleReplyInput(item.discussId)">回复</el-button>
            <el-button 
              v-if="isAdmin||userStore.getToken() && item.uid===userStore.getUserInfo().uid"
              type="text" 
              style="color: #F56C6C"
              @click="deleteComment(item.discussId)">
              删除
            </el-button>
          </div>
        </div>
        <p class="comment-content" >{{ item.content }}</p>
        <span class="comment-time">{{ formatDateToDetail(item.createTime) }}</span>
        
        <!-- 回复输入框 -->
        <div v-if="showReplyInput === item.discussId" class="reply-input-container">
          <el-input 
            v-model="replyContent" 
            type="textarea" 
            rows="2" 
            placeholder="请输入回复内容">
          </el-input>
          <div style="text-align:right;">
            <el-button type="primary" size="small" @click="submitReply(item.discussId,item.uid)" style="margin-top: 10px">
              发送
            </el-button>
          </div>
        </div>

        <div v-if="item.replies && item.replies.length > 0" class="replies-control">
          <el-button 
            type="text" 
            @click="toggleReplies(item.discussId)"
          >
            {{ expandedComments.includes(item.discussId) ? '收起' : `展开 ${item.replies.length} 条回复` }}
          </el-button>
        </div>

        <div v-if="item.replies.length > 0 && expandedComments.includes(item.discussId)" class="replies">
          <div v-for="child in item.replies" :key="child.discussId" class="reply">
            <div style="display: flex; justify-content: space-between; align-items: center">
              <div class="user-info">
                <el-avatar :size="30" :src="child.avatar?child.avatar:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"></el-avatar>
                <span class="reply-author">{{ child.publisherName }}: </span>
              </div>
              <el-button 
                v-if="isAdmin||userStore.getToken() && child.uid===userStore.getUserInfo().uid"
                type="text"
                style="color: #F56C6C"
                @click="deleteComment(child.discussId)">
                删除
              </el-button>
            </div>
            <span class="reply-content" style="margin-left: 40px">{{ child.content }}</span>
            <span class="reply-time">{{ formatDateToDetail(child.createTime) }}</span>
          </div>
        </div>
      </div>

    </div>

    <!-- 悬浮工具条 -->
    <div class="floating-toolbar">
      <el-tooltip v-if="isAdmin||isMyPost" content="删除" placement="right" >
        <div style="height: 50px;padding-top: 10px">
          <el-button text @click="deleteNote">
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </el-tooltip>
      <div class="divider"></div>

      <el-tooltip v-if="(isAdmin||isMyPost)&&data.status==='0'" content="关闭" placement="right" >
        <div style="height: 50px;padding-top: 10px">
          <el-button text @click="openAndCloseNote('close')">
            <el-icon><Lock /></el-icon>
          </el-button>
        </div>
      </el-tooltip>

      <el-tooltip v-if="(isAdmin||isMyPost)&&data.status==='1'" content="解锁" placement="right" >
        <div style="height: 50px;padding-top: 10px">
          <el-button text @click="openAndCloseNote('unlock')">
            <el-icon><Unlock /></el-icon>
          </el-button>
        </div>
      </el-tooltip>

      <div class="divider"></div>
      <el-tooltip v-if="isMyPost" content="编辑" placement="right" >
        <div style="height: 50px;padding-top: 10px">
          <el-button text @click="handleEditNote">
            <el-icon><Edit /></el-icon>
          </el-button>
        </div>
      </el-tooltip>
      <div class="divider"></div>
      <el-tooltip content="发帖" placement="right" >
        <div style="height: 50px;padding-top: 10px">
          <el-button text @click="handlePostNote">
            <el-icon><Plus /></el-icon>
          </el-button>
        </div>
      </el-tooltip>
      <div class="divider"></div>
      <el-tooltip content="刷新" placement="right">
        <div style="height: 50px;padding-top: 10px">
          <el-button text @click="refreshPage">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </div>
      </el-tooltip>
      <div class="divider"></div>

      <el-tooltip content="回到顶部" placement="right">
        <div style="height: 50px;padding-top: 10px">
          <el-button text @click="scrollToTop">
            <el-icon><Top /></el-icon>
          </el-button>
        </div>
      </el-tooltip>
    </div>

    <!-- 发帖 Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="mode==='post'? '发布帖子':'编辑帖子'"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleDialogClose"
    >
      <postNote  ref="postNoteRef"  :initialData="tempData" :mode="mode"/>
    </el-dialog>

  </div>
</div>

</template>

<style scoped>
.body{
  background-color: #f5f7fa;
  justify-items: center;
}

.dataTable{
  padding:20px 100px;
  width: 1100px;
  min-height: 700px;
  height: auto;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.notice{
  border-radius: 10px;
  margin-top: 20px;
  margin-bottom: 20px;
  width: 1100px;
  padding: 15px;
  background-color: #ffffff;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.discussArea {
  width: 1100px;
  margin-top: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.comment {
  min-height: 130px;
  height: auto;
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  background-color: #ffffff;
}

.comment-author {
  font-weight: bold;
  color: #333;
}

.comment-content {
  margin: 5px 0;
  color: #555;
}
.comment-time{
  color: rgba(121, 121, 121, 0.77);
  float: right;
  font-size: 12px;
  margin-bottom: 0px;
}
.replies {

  margin-top: 10px;
  padding-left: 15px;
  border-left: 2px solid #e0e0e0;
}

.reply {
  min-height: 55px;
  height: auto;
  margin-top: 5px;
}
.reply-time{
  color: rgba(121, 121, 121, 0.77);
  float: right;
  font-size: 12px;
  margin-bottom: 0px;
}
.reply-author {
  font-size: 14px;
  color: #007bff;
}

.reply-content {
  margin-top: 5px;
  margin-left: 10px;
  color: #666;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.reply-input-container {
  margin: 10px 0;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.reply .user-info {
  margin-bottom: 5px;
}

.replies-control {
  margin: 10px 0;
  color: #409EFF;
  cursor: pointer;
}

.floating-toolbar {
  position: fixed;
  left: calc(50% + 570px);
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 999;
}

.floating-toolbar .el-button {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.floating-toolbar .el-icon {
  font-size: 24px;
}

.divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 0;
}

.submit-clue-button{
  width: 100%;
  height: 40px;
  font-size: 14px;
  background-color: #ff6800;
  color: white;
  margin-top: 30px
}

.ban-submit-clue-button{
  width: 100%;
  height: 40px;
  font-size: 14px;
  background-color: #cccccc;
  color: #ffffff;
  margin-top: 30px
}

.ban-submit-clue-button:hover{
  cursor: not-allowed;
}
</style>